package com.zhiqianbao.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.zhiqianbao.R;
import com.zhiqianbao.application.MyApplication;
import com.zhiqianbao.share.ShareUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.WorthPurseUtil;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.tauth.Tencent;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by 子龙 on 2017/7/28.
 * 活动H
 */
public class Big_PicDialogActivity extends BaseActivity implements View.OnClickListener {

    private WebView vebview ;
    private Button button_ruturn;
    private ImageView share_img;
    private Dialog mShareDialog;
    private String shareImgUrl="";
    private String shareContent="";
    private String shareUrl="";
    private String shareTitle="";
    private LinearLayout loading_layout;
    private ProgressBar zhima_progressBar;
    private UMShareAPI mShareAPI;
    private boolean isInstallWeChat;
    private boolean isInstallQQ;
    private Bitmap shareBmap;
    private boolean clickDownImg=false;
    private ShareUtils shareUtils;
    private int shareType=0;
    private Tencent _tencent;
    public Handler imgHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            shareBmap=(Bitmap) msg.obj;
            if(clickDownImg){
                clickDownImg=false;
                shareUtils.shareWxFriends(shareType,shareUrl,shareTitle,shareContent,shareBmap);
            }
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picialog);
        shareUtils=new ShareUtils();
        _tencent = Tencent.createInstance("1105139983", this);
        mShareAPI = UMShareAPI.get(this);
        initview();
        initData();
        addListner();
    }

    private void addListner() {
        button_ruturn.setOnClickListener(this);
        share_img.setOnClickListener(this);
    }

    private void initData() {
        // "/basic/checkUpdate?mimidaiVersion=" + Constants.APP_VERSION)
        //获取当前系统时间
        long timeStamp = System.currentTimeMillis();
        final String checkweb_url = getIntent().getExtras().getString("checkweb");
        final int activityid = getIntent().getExtras().getInt("activityid");
        shareImgUrl= getIntent().getExtras().getString("shareImgUrl");
        shareContent= getIntent().getExtras().getString("shareContent");
        shareTitle= getIntent().getExtras().getString("shareTitle");
        WebSettings settings = vebview.getSettings();
        //wv_reg_protocol.loadData(data, "text/html; charset=UTF-8", null);//解决中文乱码

        // 显示完整网页
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);

        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setSavePassword(true);
        settings.setBuiltInZoomControls(true); // 显示放大缩小 controler
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setSupportZoom(true); // 可以缩放
        settings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE);// 默认缩放模式
        // 清除缓存和记录
        vebview.clearCache(true);
        vebview.clearHistory();
        vebview.setWebViewClient(new WebViewClient());
        settings.setDomStorageEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);// 解决三星note4显示不全

//        vebview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        vebview.setVerticalScrollBarEnabled(false);
        vebview.setVerticalScrollbarOverlay(false);
        vebview.setHorizontalScrollBarEnabled(false);
        vebview.setHorizontalScrollbarOverlay(false);
        vebview.setWebViewClient(new WebViewClient(){
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
                handler.proceed();
            }
        });
        vebview.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                try{
                    if (!TextUtils.isEmpty(String.valueOf(newProgress))){
                        if(newProgress==100){
                            loading_layout.setVisibility(View.GONE);
                        }else{
                            loading_layout.setVisibility(View.VISIBLE);
                        }
                    }

                }catch (Exception e){

                }

                super.onProgressChanged(view, newProgress);
            }
        });

        try{
            if (Constants.LOGIN_USER==null){
                startActivity(new Intent(Big_PicDialogActivity.this,
                        WorthPurseUtil.getZhiddActivity().getClass())
                        .putExtra("bptag",1));
                Big_PicDialogActivity.this.finish();
                finish();

            }else {
                vebview.loadUrl(checkweb_url+"?activityId="+activityid+"&userId="+ Constants.LOGIN_USER.getId()+"&timestamp="+ String.valueOf(timeStamp));
            }
            shareUrl=checkweb_url+"?activityId="+activityid+"&userId="+ Constants.LOGIN_USER.getId();
        }catch (Exception e){}

        downShareImg();
    }


    private void initview() {
        vebview = (WebView) findViewById(R.id.web_view);
        button_ruturn = (Button) findViewById(R.id.button_ruturn);
        share_img= (ImageView) findViewById(R.id.share_img);
         loading_layout = (LinearLayout)findViewById(R.id.loading_layout);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isInstallWeChat= MyApplication.mWxApi.isWXAppInstalled();
        isInstallQQ= mShareAPI.isInstall(Big_PicDialogActivity.this, SHARE_MEDIA.QQ);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CookieSyncManager.createInstance(this);
        CookieManager instance = CookieManager.getInstance();
        instance.removeAllCookie();
        CookieSyncManager.getInstance().sync();
        vebview.setWebChromeClient(null);
        vebview.setWebViewClient(null);
        vebview.getSettings().setJavaScriptEnabled(false);
        vebview.clearCache(true);
        shareBmap.recycle();
        shareBmap=null;
    }

    @Override
    public void onClick(View v) {
        if(R.id.button_ruturn==v.getId()) {
            finish();
        }
        else if(R.id.share_img==v.getId()){
                showDialog();
        }
    }

    /**
     * 显示分享弹出框
     */
    private void showDialog() {
        if (mShareDialog == null) {
            initShareDialog();
        }
        mShareDialog.show();
    }

    /**
     * 下载分享图片
     */
    public void downShareImg(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap=getNetWorkBitmap(shareImgUrl);
                Message msg=new Message();
                msg.obj=bitmap;
                imgHandler.sendMessage(msg);
            }
        }).start();
    }
    /**
     * 初始化分享弹出框
     */
    private void initShareDialog() {
        mShareDialog = new Dialog(this, R.style.dialog_bottom_full);
        mShareDialog.setCanceledOnTouchOutside(true);
        mShareDialog.setCancelable(true);
        Window window = mShareDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.share_animation);
        View view = View.inflate(this, R.layout.dialog_share_layout, null);
        LinearLayout wechat_share=(LinearLayout)view.findViewById(R.id.wechat_share);
        LinearLayout wechat_friend_share=(LinearLayout)view.findViewById(R.id.wechat_friend_share);
        LinearLayout sina_share=(LinearLayout)view.findViewById(R.id.sina_share);
        LinearLayout qq_share=(LinearLayout)view.findViewById(R.id.qq_share);
        TextView share_cancel=(TextView)view.findViewById(R.id.share_cancel);
        share_cancel.setOnClickListener(shareClick);
        wechat_share.setOnClickListener(shareClick);
        wechat_friend_share.setOnClickListener(shareClick);
        sina_share.setOnClickListener(shareClick);
        qq_share.setOnClickListener(shareClick);
        window.setContentView(view);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
    }

    View.OnClickListener shareClick=new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(R.id.wechat_share==v.getId()){

                if (isInstallWeChat) {
                    clickDownImg=true;
                    shareType=SendMessageToWX.Req.WXSceneSession;
                    if(shareBmap!=null){
                        shareUtils.shareWxFriends(shareType,shareUrl,shareTitle,shareContent,shareBmap);
                    }
                    else{
                        downShareImg();
                    }
                } else {
                    showShortToast1("抱歉，分享失败，请先安装微信客户端！");
                }
            }
            else if(R.id.wechat_friend_share==v.getId()) {
                    if (isInstallWeChat) {
                        clickDownImg=true;
                        shareType=SendMessageToWX.Req.WXSceneTimeline;
                        if(shareBmap!=null){
                            shareUtils.shareWxFriends(shareType,shareUrl,shareTitle,shareContent,shareBmap);
                        }
                        else{
                            downShareImg();
                        }
                    } else {
                        showShortToast1("抱歉，分享失败，请先安装微信客户端！");
                    }
            }
            else if(R.id.sina_share==v.getId()){
//                ShareUtils.shareWeb(Big_PicDialogActivity.this, shareUrl, shareTitle, shareContent,
//                        shareImgUrl, R.drawable.ic_launcher, SHARE_MEDIA.SINA);
            }
            else if(R.id.qq_share==v.getId()) {
                if (isInstallQQ) {
                    shareUtils.shareQQ(_tencent,Big_PicDialogActivity.this,
                            shareUrl,shareTitle,shareContent,shareImgUrl);
                } else {
                    showShortToast1("抱歉，分享失败，请先安装QQ客户端！");
                }
            }
            else if(R.id.share_cancel==v.getId()) {

            }
            if (mShareDialog != null && mShareDialog.isShowing()) {
                mShareDialog.dismiss();
            }
          }
    };

    /**
     * 获取网络图片
     * @param urlString
     * @return
     * @date 2014.05.10
     */
    public static Bitmap getNetWorkBitmap(String urlString) {
        URL imgUrl = null;
        Bitmap bitmap = null;
        try {
            imgUrl = new URL(urlString);
            // 使用HttpURLConnection打开连接
            HttpURLConnection urlConn = (HttpURLConnection) imgUrl
                    .openConnection();
            urlConn.setDoInput(true);
            urlConn.connect();
            // 将得到的数据转化成InputStream
            InputStream is = urlConn.getInputStream();
            // 将InputStream转换成Bitmap
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            System.out.println("[getNetWorkBitmap->]MalformedURLException");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("[getNetWorkBitmap->]IOException");
            e.printStackTrace();
        }
        return bitmap;
    }
}
